package com.star.eastern.blee

import android.content.Intent
import android.os.Build
import android.os.Build.VERSION_CODES.P
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.ToggleButton
import com.star.eastern.blee.fragments.DevicePage
import com.star.eastern.blee.fragments.ScanPage
import com.star.eastern.blee.fragments.SwitchPage
import com.star.eastern.blee.utils.CommandCenter
import com.star.eastern.blee.utils.LogConsole
import com.star.eastern.blee.utils.Tripple7BluetoothCommandProtocol
import com.star.eastern.blee.utils.Tripple7BluetoothCommandProtocol.Companion.dialog
import com.star.eastern.blee.utils.activity
import com.tangula.android.utils.ToastUtils

@Suppress("NAME_SHADOWING")
class MainActivity : BleeMainActivity() {

    private var mDrawerLayout: DrawerLayout? = null
    private var mDrawerToggle: ActionBarDrawerToggle? = null
    private val mToggleBtn: Array<ToggleButton?> = arrayOfNulls(3)
    private var currentPage = 0
    internal lateinit var fragments: Array<Fragment?>
    private var vwLogPageBtn:Button? = null

    fun disableScanTab(){
        mToggleBtn[0]?.also {
            it.isEnabled = false
        }
    }

    fun enableScanTab(){
        mToggleBtn[0]?.also {
            it.isEnabled = true
        }
    }

    fun disableSwitchAndAvDeviceTab(){
        mToggleBtn[1]?.also {
            it.isEnabled = false
        }
        mToggleBtn[2]?.also {
            it.isEnabled = false
        }
    }

    fun enableSwitchAndAvDeviceTab(){
        mToggleBtn[1]?.also {
            it.isEnabled = true
        }
        mToggleBtn[2]?.also {
            it.isEnabled = true
        }
    }

    @Suppress("DEPRECATION")
    override fun onCreate(savedInstanceState: Bundle?) {
        activity = this
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.requestPermissions(arrayOf("android.permission.INTERNET"), 1234)
        }

        vwLogPageBtn = findViewById(R.id.button)
        if(LogConsole.viewLogState){
            vwLogPageBtn!!.visibility = View.VISIBLE
        }else{
            vwLogPageBtn!!.visibility = View.GONE
        }
        vwLogPageBtn!!.setOnClickListener {
            val localIntent = Intent(this, ViewLogActivity::class.java)
            startActivity(localIntent)
        }

        mDrawerLayout = findViewById(R.id.drawer_layout)
        mDrawerToggle = ActionBarDrawerToggle(this,
                mDrawerLayout,
                R.string.app_name,
                R.string.app_name
        )
        mDrawerLayout!!.setDrawerListener(mDrawerToggle)
        mDrawerToggle!!.syncState()

        mToggleBtn[0] = findViewById(R.id.btn_scan)
        mToggleBtn[0]?.tag=0
        mToggleBtn[1] = findViewById(R.id.btn_switch)
        mToggleBtn[1]?.tag=1
        mToggleBtn[2] = findViewById(R.id.btn_device)
        mToggleBtn[2]?.tag=2

        enableScanTab()
        disableSwitchAndAvDeviceTab()


        fragments = arrayOfNulls(mToggleBtn.size)

        mToggleBtn.forEach {
            it?.also {
                it.setOnClickListener{
                    switchPage(it.tag as Int)
                }
            }
        }

        this.switch2BleScanPage()
    }

    private fun switchPage(index:Int){
        //LogConsole.writeBizLog("swith page $index")
        mToggleBtn.forEach {cur->
            cur?.isChecked = cur!!.tag == index
            currentPage = index
            setFragmentPage(index)
        }
    }

    fun switch2BleScanPage(){
        switchPage(0)
    }

    fun switch2SwitchControlPage(){
        switchPage(1)
        dialog?.dismiss()
        dialog = null
    }

    @Suppress("unused")
    fun switch2AvDeviceControllPage(){
        switchPage(2)
    }

    private fun setFragmentPage(index: Int) {

        val ft = supportFragmentManager.beginTransaction()
        if (fragments[index] == null) {
            when (index) {
                0 -> fragments[index] = ScanPage()
                1 -> fragments[index] = SwitchPage()
                2 -> fragments[index] = DevicePage()
            }
        }

        when(index){
            1-> CommandCenter.regOnStatUpdateListener { txt-> (fragments[index] as SwitchPage).onStatusUpdate(txt) }
            2-> CommandCenter.regOnStatUpdateListener { txt-> (fragments[index] as DevicePage).onStatusUpdate(txt) }
            3-> CommandCenter.regOnStatUpdateListener { }
        }

        fragments[index]?.let { ft.replace(R.id.replaceHolder, it) }
        ft.commit()
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        val inflater = menuInflater
        inflater.inflate(R.menu.action_menu, menu)
        return true
    }



    fun onSelectDevice(dv: ScanPage.DeviceObject) {

        super.adapter?.also { ada->

            var found = false
            ada.bondedDevices.forEach {
                if(it.address == dv.deviceAddress){
                    //Log.v("console", "found the binded device")
                    found = true
                    Tripple7BluetoothCommandProtocol.connectDevice(it,
                        {
                            LogConsole.writeBizLog("device connected:${dv.deviceName} ${dv.deviceAddress}")
                            this.disableScanTab()
                            this.enableSwitchAndAvDeviceTab()
                            this.switch2SwitchControlPage()
                        },
                        {e->
                            //LogConsole.writeBizLog("connect fail", e)
                        })
                }
            }
            if(!found) {
                Tripple7BluetoothCommandProtocol.connectDevice(ada.getRemoteDevice(dv.deviceAddress),
                    {
                        LogConsole.writeBizLog("device connected:${dv.deviceName} ${dv.deviceAddress}")
                        this.disableScanTab()
                        this.enableSwitchAndAvDeviceTab()
                        this.switch2SwitchControlPage()
                    },
                    {e->
                        //LogConsole.writeBizLog("connect fail", e)
                    })
            }
        }


    }

    fun onError2Scan(task:()->Unit){
        try{
            task()
        }catch (ex:kotlin.Exception){
            ToastUtils.showToastResLong(R.string.conn_break)
            switch2BleScanPage()
            LogConsole.writeBizLog("some ex onError2Scan", ex)
        }
    }

    override fun onBtDisconnected() {
        switch2BleScanPage()
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        //Log.v("console", "Item:${item?.itemId}")

        if(item?.itemId == R.id.action_exit){
            finish()
            return  true
        }

        return super.onOptionsItemSelected(item)
    }
}
